#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/5/8
# @Author  : suk
# @File    : product.py
# @Software: PyCharm
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django.db.models import F

from common.API.res_josn_data import fail_api, success_api
from product.forms.shipments_product import ShipmentsForm
from product.models import Product, Shipments


class ShipmentsPage(View):
    http_method_names = ['get']

    def get(self, request, *args, **kwargs):
        return render(request, 'shipments_manage/page.html')


class ShipmentsList(View):
    http_method_names = ['get']

    def get(self, request, *args, **kwargs):
        count: int = Shipments.objects.count()
        shipments_objs = Shipments.objects.all()
        data_list = []
        for s in shipments_objs:
            data_list.append({
                'id': s.pk,
                'name': s.fk_product.name,
                'product_quantity': s.fk_product.quantity,
                'quantity': s.quantity,
            })
        return JsonResponse({
            "code": 0,
            "msg": "",
            "count": count,
            "data": data_list
        })


class ShipmentsSend(View):
    http_method_names = ['get', 'post']

    def get(self, request, *args, **kwargs):
        products = Product.objects.values('pk', 'name')
        return render(request, 'shipments_manage/send.html', {'products': products})

    def post(self, request, *args, **kwargs):
        # 检查产品是否还存在
        product_objs = Product.objects.select_for_update(nowait=True).filter(pk=request.POST.get('fk_product'))
        with transaction.atomic():
            for product_obj in product_objs:
                if not product_obj:
                    return fail_api(msg='产品不存在')
            req_quantity = request.POST.get('quantity')
            # 检查产品数量是否为0和检查产品数量扣除后是否为负数
            if product_obj.quantity < 0 or (product_obj.quantity - int(req_quantity)) < 0:
                return fail_api(msg='产品数量不足')
            forms = ShipmentsForm(data=request.POST)
            if forms.is_valid():
                forms.save()
                # 更新产品表的数量
                Product.objects.filter(pk=product_obj.pk).update(quantity=F('quantity') - req_quantity)
                return success_api(msg='出库成功')
